package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.utils.FileUploader;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.UUID;

//进行文件上传和下载
@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

 /*   @Value("${reggie.path}")
    private String basePath;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        //file是一个临时文件,需要进行转存;否则本次请求后会被删除
        //获取原始文件名:t4.jpg  拆分
        String originalFilename = file.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index);//.jpg
        //生成uuid,保存的新文件名
        String uuid = UUID.randomUUID().toString();
        String fileName = uuid + substring;
        //判断文件夹是否存在
        File dir = new File(basePath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }

    @GetMapping("/download")
    public void download(String name,HttpServletResponse response){
        try {
            //获取当前文件路径,输入流读取,输出流写回浏览器
            FileInputStream fis=new FileInputStream(new File(basePath+name));
            ServletOutputStream os = response.getOutputStream();
            IOUtils.copy(fis,os);
            fis.close();
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }*/

    @Autowired
    private FileUploader fileUploader;

    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        String fileName = null;
        try {
            fileName = fileUploader.upload(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return R.success(fileName);
    }
}
